﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web.Security;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Tesla.Service.DataContracts;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using System.ServiceModel;
using Tesla.Service.WcfServiceCommon;
//using Telerik.Web.UI;
using Tesla.Util.Utilities;
using System.IO;

namespace Tesla.Web.Pages
{
    public partial class ClientDetails : PageBase
    {
        #region Class Level Variables
        private ClientServiceDispatcher clientDispatcher = null;
        private int? ClientRecordCount = 0;
        #endregion


        protected void Page_Load(object sender, EventArgs e)
        {
            List<ClientDC> clients = null;
            IList<BaseDC> clientParents = null, OUs = null;

            clientDispatcher = new ClientServiceDispatcher();

            try
            {
                if (!IsPostBack)
                {
                    if (Request.QueryString["ID"] != null)
                    {
                        clients = clientDispatcher.ReadClient(Convert.ToInt32(Request.QueryString["ID"])).Cast<ClientDC>().ToList();
                        SetValuesForControls(clients);
                        Legend1.InnerText = "Update Client";
                    }

                    else
                    {
                        clientParents = clientDispatcher.ReadAllClients().Cast<BaseDC>().ToList();
                        OUs = clientDispatcher.ReadAllOperatingUnits().Cast<BaseDC>().ToList();

                        ArrayList arrClientparents = new ArrayList(), arrOperatingUnits = new ArrayList();

                        if (clientParents != null && clientParents.Count > 0)
                        {
                            foreach (BaseDC cpDC in clientParents)
                            {
                                arrClientparents.Add((ClientParentDC)cpDC);
                            }
                        }

                        if (OUs != null && OUs.Count > 0)
                        {
                            foreach (BaseDC cpDC in OUs)
                            {
                                arrOperatingUnits.Add((OperatingUnitDC)cpDC);
                            }
                        }

                        ddlClientParentName.DataValueField = "ClientID"; ddlClientParentName.DataTextField = "ClientName";
                        ddlClientOperatingUnit.DataValueField = "OperatingUnitID"; ddlClientOperatingUnit.DataTextField = "OperatingUnitDescription";
                        this.ddlClientParentName.DataSource = arrClientparents;
                        this.ddlClientParentName.DataBind();
                        this.ddlClientOperatingUnit.DataSource = arrOperatingUnits;
                        this.ddlClientOperatingUnit.DataBind();
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                int? ClientID = 0, success = 0;
                ClientDC createdClient = new ClientDC();
                createdClient.ClientName = txtClientName.Text;
                createdClient.ClientParentName = ddlClientParentName.SelectedItem.Text;
                createdClient.ClientParentID = Convert.ToInt32( ddlClientParentName.SelectedItem.Value);
                createdClient.ClientGeo = txtClientGeo.Text;
                createdClient.Client_OU = ddlClientOperatingUnit.SelectedItem.Text;
                createdClient.Client_OUID = Convert.ToInt32(ddlClientOperatingUnit.SelectedItem.Value);

                clientDispatcher = new ClientServiceDispatcher();

                if (ViewState["SelectedClientId"] == null)
                {
                    ClientID = clientDispatcher.CreateClient(createdClient);
                }
                else
                {
                    createdClient.ClientID = Convert.ToInt32(ViewState["SelectedClientId"]);
                    success = clientDispatcher.UpdateClient(createdClient);
                }
                if (!Page.ClientScript.IsClientScriptBlockRegistered("saveAlert"))
                {
                    Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "saveAlert", "alert('Data has been succesfully saved '); window.location.href('ClientSearch.aspx')", true);
                }


            }

            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void SetValuesForControls(List<ClientDC> clients)
        {
            ViewState["SelectedClientId"] = ((ClientDC)clients[0]).ClientID;
            this.txtClientName.Text = ((ClientDC)clients[0]).ClientName;

            ArrayList arrClientparents = new ArrayList(), arrOperatingUnits = new ArrayList();

            if (clients != null && ((ClientDC)clients[0]).ClientParents != null && ((ClientDC)clients[0]).ClientParents.Count > 0)
            {
                foreach (BaseDC cpDC in ((ClientDC)clients[0]).ClientParents)
                {
                    arrClientparents.Add((ClientParentDC)cpDC);
                }
            }

            if (clients != null && ((ClientDC)clients[0]).ClientOperatingUnits != null && ((ClientDC)clients[0]).ClientOperatingUnits.Count > 0)
            {
                foreach (BaseDC cpDC in ((ClientDC)clients[0]).ClientOperatingUnits)
                {
                    arrOperatingUnits.Add((OperatingUnitDC)cpDC);
                }
            }

            ddlClientParentName.DataValueField = "ClientID"; ddlClientParentName.DataTextField = "ClientName";
            ddlClientOperatingUnit.DataValueField = "OperatingUnitID"; ddlClientOperatingUnit.DataTextField = "OperatingUnitDescription";
            this.ddlClientParentName.DataSource = arrClientparents;
            this.ddlClientParentName.DataBind();
            this.ddlClientOperatingUnit.DataSource = arrOperatingUnits;
            this.ddlClientOperatingUnit.DataBind();
            this.ddlClientParentName.SelectedValue = ((ClientDC)clients[0]).ClientParentID.ToString();
            this.ddlClientOperatingUnit.SelectedValue = ((ClientDC)clients[0]).Client_OUID.ToString();
            this.txtClientGeo.Text = ((ClientDC)clients[0]).ClientGeo;

            clientDispatcher = new ClientServiceDispatcher();

            if (((ClientDC)clients[0]).ClientID != null)
            {
                IList<BaseDC> projects = clientDispatcher.ReadProjectsForClient(((ClientDC)clients[0]).ClientID).ToList();
                DataTable projectTable = new DataTable("Projects");

                if (projectTable.Columns.Count == 0)
                    projectTable.Columns.AddRange(new DataColumn[]{
                                                     new DataColumn("ProjectCode", typeof(string)),
                                                     new DataColumn("ProjectBillingType", typeof(int)),
                                                     new DataColumn("ProjectType", typeof(int)),
                                                     new DataColumn("ProjectPlannedStartDate", typeof(DateTime)),
                                                     new DataColumn("ProjectPlannedEndDate", typeof(DateTime)),
                                                     new DataColumn("ProjectCompletionPct", typeof(float))});

                foreach (BaseDC bDC in projects)
                {
                    DataRow dr = projectTable.NewRow();
                    dr["ProjectCode"] = ((ProjectDC)bDC).ProjectCode;
                    dr["ProjectBillingType"] = ((ProjectDC)bDC).ProjectBillingType;
                    dr["ProjectType"] = ((ProjectDC)bDC).ProjectType;
                    dr["ProjectPlannedStartDate"] = ((ProjectDC)bDC).ProjectPlannedStartDate;
                    dr["ProjectPlannedEndDate"] = ((ProjectDC)bDC).ProjectPlannedEndDate;
                    dr["ProjectCompletionPct"] = ((ProjectDC)bDC).ProjectCompletionPct;
                    projectTable.Rows.Add(dr);
                }

                grdProjects.DataSource = projectTable;
                grdProjects.DataBind();
            }

          
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            try
            {
                Response.Redirect(VirtualPathUtility.ToAbsolute("~/") + @"Pages/Administrator/ClientSearch.aspx", false);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
